

package com.maoshi.shop.delivery.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoshi.shop.bean.enums.OrderStatus;
import com.maoshi.shop.bean.model.Order;
import com.maoshi.shop.bean.model.OrderItem;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.dao.OrderItemMapper;
import com.maoshi.shop.delivery.comment.dao.DeliveryOrderMapper;
import com.maoshi.shop.delivery.comment.model.DeliveryOrder;
import com.maoshi.shop.delivery.comment.model.DeliveryOrderItem;
import com.maoshi.shop.delivery.comment.param.DeliveryOrderItemParam;
import com.maoshi.shop.delivery.comment.service.DeliveryOrderItemService;
import com.maoshi.shop.delivery.comment.service.DeliveryOrderService;
import com.maoshi.shop.service.OrderService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 *
 * @author lhd
 * @date 2020-04-22 15:46:05
 */
@Service
@AllArgsConstructor
public class DeliveryOrderServiceImpl extends ServiceImpl<DeliveryOrderMapper, DeliveryOrder> implements DeliveryOrderService {

    private final DeliveryOrderMapper deliveryOrderMapper;
    private final DeliveryOrderItemService deliveryOrderItemService;
    private final OrderService orderService;
    private final OrderItemMapper orderItemMapper;
    private final MapperFacade mapperFacade;
    /**
     * 生成物流信息及保存物流与订单关联
     * @param deliveryOrderParam 物流信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDeliveriesInfo(DeliveryOrderItemParam deliveryOrderParam) {
        List<OrderItem> selectOrderItems = deliveryOrderParam.getSelectOrderItems();
        String orderNumber = deliveryOrderParam.getOrderNumber();
        //校验数量及获取发货的总数
        int prodNumSum = checkDelivery(selectOrderItems);
        DeliveryOrder deliveryOrder = new DeliveryOrder();
        deliveryOrder.setOrderNumber(deliveryOrderParam.getOrderNumber());
        deliveryOrder.setDvyId(deliveryOrderParam.getDvyId());
        deliveryOrder.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
        deliveryOrder.setCreateTime(new Date());
        deliveryOrder.setStatus(1);
        deliveryOrder.setProductNums(prodNumSum);
        //保存订单物流信息
        save(deliveryOrder);
        //保存需要添加的关联信息
        List<DeliveryOrderItem> addDeliveries = new ArrayList<>();
        for (OrderItem selectOrderItem : selectOrderItems) {
            DeliveryOrderItem deliveryOrderItem = new DeliveryOrderItem();
            deliveryOrderItem.setOrderItemId(selectOrderItem.getOrderItemId());
            deliveryOrderItem.setProdCount(selectOrderItem.getChangeNum());
            deliveryOrderItem.setOrderDeliveryId(deliveryOrder.getOrderDeliveryId());
            addDeliveries.add(deliveryOrderItem);
        }
        if(CollectionUtils.isNotEmpty(addDeliveries)){
            deliveryOrderItemService.saveBatch(addDeliveries);
            orderItemMapper.updateByDeliveries(selectOrderItems);
            //判断是否发货完成
            List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderNumber));
            boolean isDelivery = true;
            for (OrderItem orderItem : orderItems) {
                if(orderItem.getStatus() != 0){
                    isDelivery = false;
                }
            }
            //修改为发货状态
            if(isDelivery){
                orderService.update(new LambdaUpdateWrapper<Order>()
                            .set(Order::getStatus, OrderStatus.CONSIGNMENT.value())
                            .set(Order::getUpdateTime,new Date())
                            .set(Order::getDvyTime,new Date())
                            .set(Order::getDvyType,1)
                            .eq(Order::getOrderNumber,orderNumber));
            }
        }
    }

    /**
     * 修改物流信息
     * @param deliveryOrders 物流修改的信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderDeliveries(List<DeliveryOrder> deliveryOrders) {
        List<DeliveryOrder> addDeliveryOrders = new ArrayList<>();
        for (DeliveryOrder deliveryOrder : deliveryOrders) {
            //需要新增的物流信息
            DeliveryOrder addDeliveryOrder = mapperFacade.map(deliveryOrder, DeliveryOrder.class);
            addDeliveryOrder.setCreateTime(new Date());
            addDeliveryOrder.setStatus(1);
            addDeliveryOrders.add(addDeliveryOrder);
            //修改之前的状态为删除，恢复之前的物流信息
            deliveryOrder.setDvyId(null);
            deliveryOrder.setDvyFlowId(null);
            deliveryOrder.setDeleteTime(new Date());
            deliveryOrder.setStatus(-1);
        }
        updateBatchById(deliveryOrders);
        saveBatch(addDeliveryOrders);
    }

    /**
     * 校验可发货数量并返回总数
     * @param selectOrderItems 选择发货的订单项
     */
    private int checkDelivery(List<OrderItem> selectOrderItems) {
        //查询已发货数量
        List<DeliveryOrderItem> deliveryOrderItemList = deliveryOrderItemService.listItemNums(selectOrderItems);
        //判断可发货数量
        if(CollectionUtils.isNotEmpty(deliveryOrderItemList)){
            Map<Long, Integer> deliveryMap = deliveryOrderItemList.stream().collect(
                    Collectors.toMap(DeliveryOrderItem::getOrderItemId, DeliveryOrderItem::getProdCount));
            for (OrderItem selectOrderItem : selectOrderItems) {
                if(!deliveryMap.containsKey(selectOrderItem.getOrderItemId())){
                    continue;
                }
                Integer prodCount = deliveryMap.get(selectOrderItem.getOrderItemId());
                if(prodCount > selectOrderItem.getChangeNum()){
                    throw new MaoshiShopBindException("部分订单可发货数量不足！");
                }
            }
        }
        //获取发货总数
        int prodNumSum = 0;
        for (OrderItem selectOrderItem : selectOrderItems) {
            prodNumSum += selectOrderItem.getChangeNum();
        }
        return prodNumSum;
    }
}
